package com.riche.codefactory.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.riche.codefactory.common.ErrorCode;
import com.riche.codefactory.constant.CommonConstant;
import com.riche.codefactory.exception.ThrowUtils;
import com.riche.codefactory.mapper.QuestionMapper;
import com.riche.codefactory.model.c2s.question.C2sQuestionQueryRequest;
import com.riche.codefactory.model.domain.Question;
import com.riche.codefactory.model.domain.QuestionBankQuestion;
import com.riche.codefactory.model.s2c.S2cQuestion;
import com.riche.codefactory.service.IQuestionBankQuestionSVC;
import com.riche.codefactory.service.IQuestionSVC;
import com.riche.codefactory.service.IUserSVC;
import com.riche.codefactory.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 题目服务实现
 *
 */
@Service
@Slf4j
public class QuestionSVC extends ServiceImpl<QuestionMapper, Question> implements IQuestionSVC {

    @Resource
    private IUserSVC userService;

    @Resource
    @Lazy
    private IQuestionBankQuestionSVC IQuestionBankQuestionSVC;

    /**
     * 校验数据
     *
     * @param question
     * @param add      对创建的数据进行校验
     */
    @Override
    public void validQuestion(Question question, boolean add) {
        ThrowUtils.throwIf(question == null, ErrorCode.PARAMS_ERROR);
        // todo 从对象中取值
        String title = question.getTitle();
        String answer = question.getAnswer();
        // 创建数据时，参数不能为空
        if (add) {
            // todo 补充校验规则
            ThrowUtils.throwIf(StringUtils.isBlank(title), ErrorCode.PARAMS_ERROR);
        }
        // 修改数据时，有参数则校验
        // todo 补充校验规则
        if (StringUtils.isNotBlank(title)) {
            ThrowUtils.throwIf(title.length() > 80, ErrorCode.PARAMS_ERROR, "标题过长");
        }
        if (StringUtils.isNotBlank(answer)) {
            ThrowUtils.throwIf(answer.length() > 10240, ErrorCode.PARAMS_ERROR, "答案过长");
        }
    }

    /**
     * 获取查询条件
     *
     * @param c2sQuestionQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Question> getQueryWrapper(C2sQuestionQueryRequest c2sQuestionQueryRequest) {
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        if (c2sQuestionQueryRequest == null) {
            return queryWrapper;
        }
        // todo 从对象中取值
        Long id = c2sQuestionQueryRequest.getId();
        Long notId = c2sQuestionQueryRequest.getNotId();
        String title = c2sQuestionQueryRequest.getTitle();
        String content = c2sQuestionQueryRequest.getContent();
        String searchText = c2sQuestionQueryRequest.getSearchText();
        String sortField = c2sQuestionQueryRequest.getSortField();
        String sortOrder = c2sQuestionQueryRequest.getSortOrder();
        List<String> tagList = c2sQuestionQueryRequest.getTags();
        Long userId = c2sQuestionQueryRequest.getUserId();
        String answer = c2sQuestionQueryRequest.getAnswer();
        // todo 补充需要的查询条件
        // 从多字段中搜索
        if (StringUtils.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("title", searchText).or().like("content", searchText));
        }
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        queryWrapper.like(StringUtils.isNotBlank(answer), "answer", answer);
        // JSON 数组查询
        if (CollUtil.isNotEmpty(tagList)) {
            for (String tag : tagList) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 精确查询
        queryWrapper.ne(ObjectUtils.isNotEmpty(notId), "id", notId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取题目封装
     *
     * @param question
     * @param request
     * @return
     */
    @Override
    public S2cQuestion getQuestionVO(Question question, HttpServletRequest request) {
        // 对象转封装类
        S2cQuestion s2cQuestion = S2cQuestion.objToVo(question);

        return s2cQuestion;
    }

    /**
     * 分页获取题目封装
     *
     * @param questionPage
     * @param request
     * @return
     */
    @Override
    public Page<S2cQuestion> getQuestionVOPage(Page<Question> questionPage, HttpServletRequest request) {
        List<Question> questionList = questionPage.getRecords();
        Page<S2cQuestion> questionVOPage = new Page<>(questionPage.getCurrent(), questionPage.getSize(), questionPage.getTotal());
        if (CollUtil.isEmpty(questionList)) {
            return questionVOPage;
        }
        // 对象列表 => 封装对象列表
        List<S2cQuestion> s2cQuestionList = questionList.stream().map(S2cQuestion::objToVo).collect(Collectors.toList());

        questionVOPage.setRecords(s2cQuestionList);
        return questionVOPage;
    }

    /**
     * 分页获取题目列表（仅管理员可用）
     *
     * @param c2sQuestionQueryRequest
     * @return
     */
    public Page<Question> listQuestionByPage(C2sQuestionQueryRequest c2sQuestionQueryRequest) {
        long current = c2sQuestionQueryRequest.getCurrent();
        long size = c2sQuestionQueryRequest.getPageSize();
        QueryWrapper<Question> queryWrapper = this.getQueryWrapper(c2sQuestionQueryRequest);

        // 根据题库列表查询题目列表接口 - > 使用 plus 提供的 lambda 表达式进行查询
        Long questionBankId = c2sQuestionQueryRequest.getQuestionBankId();
        if (questionBankId != null) {
            // 查询题库里面的所有题目 id
            LambdaQueryWrapper<QuestionBankQuestion> lambdaQueryWrapper = Wrappers.lambdaQuery(QuestionBankQuestion.class)
                    .select(QuestionBankQuestion::getQuestionId)
                    .eq(QuestionBankQuestion::getQuestionBankId, questionBankId);
            List<QuestionBankQuestion> questionList = IQuestionBankQuestionSVC.list(lambdaQueryWrapper);
            if (CollUtil.isNotEmpty(questionList)) {
                // 取出题目id集合
                Set<Long> questionIdSet = questionList.stream().map(QuestionBankQuestion::getQuestionId).collect(Collectors.toSet());
                queryWrapper.in("id", questionIdSet);
            } else {
                // 题库为空，则返回空列表
                return new Page<>(current, size, 0);
            }
        }

        // 查询数据库
        Page<Question> questionPage = this.page(new Page<>(current, size), queryWrapper);
        return questionPage;
    }


    /**
     * 从 ES 查询题目
     * <p>
     * //     * @param questionQueryRequest
     *
     * @param c2sQuestionQueryRequest
     * @return Page<Question>
     */
/*    @Override
    public Page<Question> searchQuestionFromEs(C2sQuestionQueryRequest c2sQuestionQueryRequest) {
        // 获取参数
        Long id = c2sQuestionQueryRequest.getId();
        Long notId = c2sQuestionQueryRequest.getNotId();
        String searchText = c2sQuestionQueryRequest.getSearchText();
        List<String> tags = c2sQuestionQueryRequest.getTags();
        Long questionBankId = c2sQuestionQueryRequest.getQuestionBankId();
        Long userId = c2sQuestionQueryRequest.getUserId();
        // 注意，ES 的起始页为 0
        int current = c2sQuestionQueryRequest.getCurrent() - 1;
        int pageSize = c2sQuestionQueryRequest.getPageSize();
        String sortField = c2sQuestionQueryRequest.getSortField();
        String sortOrder = c2sQuestionQueryRequest.getSortOrder();

        // 构造查询条件
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 过滤
        boolQueryBuilder.filter(QueryBuilders.termQuery("isDelete", 0));
        if (id != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("id", id));
        }
        if (notId != null) {
            boolQueryBuilder.mustNot(QueryBuilders.termQuery("notId", notId));
        }
        if (userId != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("userId", userId));
        }
        if (questionBankId != null) {
            // 过滤   +    等于 ：termQuery
            boolQueryBuilder.filter(QueryBuilders.termQuery("questionId", questionBankId));
        }
        // 必须包含所有标签
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                boolQueryBuilder.filter(QueryBuilders.termQuery("tags", tag));
            }
        }
        // 按关键词进行检索
        if (StringUtils.isNotBlank(searchText)) {
            // should：理解为数据库中的 or 关键字
            boolQueryBuilder.should(QueryBuilders.matchQuery("title", searchText));
            boolQueryBuilder.should(QueryBuilders.matchQuery("content", searchText));
            boolQueryBuilder.should(QueryBuilders.matchQuery("answer", searchText));
            // 最小匹配条件，只要有一个满足条件就返回
            boolQueryBuilder.minimumShouldMatch(1);
        }
        // 进行排序
        SortBuilder<?> sortBuilder = SortBuilders.scoreSort();
        if (StringUtils.isNotBlank(sortField)) {
            sortBuilder = SortBuilders.fieldSort(sortField);
            sortBuilder.order(CommonConstant.SORT_ORDER_ASC.equals(sortOrder) ? SortOrder.ASC : SortOrder.DESC);
        }
        // 分页：
        PageRequest pageRequest = PageRequest.of(current, pageSize);
        // 构造查询
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(boolQueryBuilder)
                .withPageable(pageRequest)
                .withSorts(sortBuilder)
                .build();
        SearchHits<C2sQuestionEsDTO> searchHits = elasticsearchRestTemplate.search(searchQuery, C2sQuestionEsDTO.class);

        // 复用 Mysql 的分页对象， 封装返回结果
        Page<Question> page = new Page<>();
        page.setTotal(searchHits.getTotalHits());
        ArrayList<Question> resourceList = new ArrayList<>();
        if (searchHits.hasSearchHits()) {
            List<SearchHit<C2sQuestionEsDTO>> searchHitList = searchHits.getSearchHits();
            for (SearchHit<C2sQuestionEsDTO> questionEsDTOSearchHit : searchHitList) {
                resourceList.add(C2sQuestionEsDTO.dtoToObj(questionEsDTOSearchHit.getContent()));

            }
        }
        page.setRecords(resourceList);

        return page;
    }*/

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDeleteQuestions(List<Long> questionIdList) {
        ThrowUtils.throwIf(CollUtil.isEmpty(questionIdList), ErrorCode.PARAMS_ERROR, "要删除的题目列表为空");
        for (Long questionId : questionIdList) {
            boolean result = this.removeById(questionId);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除题目失败");
            // 移除题目题库关系
            LambdaQueryWrapper<QuestionBankQuestion> queryWrapper = Wrappers.lambdaQuery(QuestionBankQuestion.class).eq(QuestionBankQuestion::getQuestionId, questionId);
            result = IQuestionBankQuestionSVC.remove(queryWrapper);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除题目题库关联失败");
        }
    }
}
